package config

import (
	"gitee.com/micro-services/tconf/config"
	"github.com/micro/go-micro/v2/config/source/etcd"
	"log"
)

// 服务全局配置
var GConf *ServerConfig

type ServerConfig struct {
	MySQL struct {
		Host     string `json:"Host"`
		Port     int    `json:"Port"`
		User     string `json:"User"`
		Password string `json:"Password"`
		DBName   string `json:"DBName"`
	} `json:"MySQL"`
	Redis struct {
		Host string `json:"Host"`
		Port int    `json:"Port"`
		DB   int    `json:"DB"`
	} `json:"Redis"`
}

var (
	Endpoint = []string{"127.0.0.1:2379", "127.0.0.1:22379", "127.0.0.1:32379"}
)

type GetConfig func(interface{}) error

func InitCfg(path string, g GetConfig) error {
	GConf = &ServerConfig{}
	source := etcd.NewSource(
		etcd.WithAddress(Endpoint...),
		etcd.WithPrefix(path),
	)

	config.Init(GConf, config.WithSource(source), config.WithPath(path))

	return g(GConf)
}

func AppConf(conf interface{}) error {
	err := config.Conf().AppConf(conf)
	if err != nil {
		log.Fatal("get app config error:", err)
		return err
	}
	return nil
}
